import express from 'express';
import Ret, { RetCode, SUCCESS } from '../../bean/code/Ret';
const app = express();
import { Op } from 'Sequelize'
import { db, Sequelize } from '../../dao/config';
import { converPage } from '../../bean/page';
import { excludeEmpty } from '../../utils';
import logger from '../../utils/logger';
import dayjs from 'dayjs'
const Order = require("../../dao/models/f_order")(db, Sequelize);
const Product = require("../../dao/models/f_product")(db, Sequelize);
const OrderProductRelation = require("../../dao/models/f_order_product_relation")(db, Sequelize);
Order.belongsToMany(Product, {
    foreignKey: "order_id",
    through: OrderProductRelation
})

Product.belongsToMany(Order, {
    foreignKey: "product_id",
    through: OrderProductRelation
})

/**
 * 查詢图标信息
 */
app.get("/report/chartInfo", async (req, res) => {
    const curMonth = [
        dayjs().startOf("month").toDate(),
        new Date()
    ];
    const monthDate = dayjs().subtract(1, "months");
    const prevMonth = [
        monthDate.startOf("month").toDate(),
        monthDate.toDate()
    ];
    async function getReport(dateRange) {
        return await Order.findAll({
            attributes: [[Sequelize.fn('SUM', Sequelize.col('total_price')), 'totalPrice'], 'createTime'], group: 'create_time', rollup: true, where: {
                createTime: {
                    [Op.between]: dateRange
                }
            }
        });
    }
    return res.json(Ret(SUCCESS).setData({
        curMonthReport: await getReport(curMonth),
        prevMonthReport: await getReport(prevMonth),
    }))

})
app.get("/report/productSaleChartInfo", async (req, res) => {
    const productReports = await Product.findAll(({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('fOrders.total_price')), 'totalPrice'], 'id', 'name'], group: 'id', rollup: true, include: { model: Order, attributes: [] }
    }));
    return res.json(Ret(SUCCESS).setData(productReports));
})
app.get("/report/businessStatistics", async (req, res) => {
    const curMonth = [
        dayjs().startOf("month").toDate(),
        new Date()
    ];
    const curDay = [
        dayjs().startOf("day").toDate(),
        new Date()
    ];
    function getReport(dateRange) {
        return Order.find({
            attributes: [[Sequelize.fn('COUNT', Sequelize.col('id')), 'totalCount'], [Sequelize.fn("AVG", Sequelize.col("total_price")), "avgPrice"], [Sequelize.fn('SUM', Sequelize.col('total_price')), 'totalPrice'], 'createTime'], rollup: true, where: {
                createTime: {
                    [Op.between]: dateRange
                }
            }
        })
    }
    const resArr = await Promise.all([getReport(curMonth), getReport(curDay)]);
    res.json([{
        dayReport:resArr[1],
        monthReport:resArr[0]
    }]);
})
export default app;
